package com.zbu.reggie.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.zbu.reggie.common.R;
import com.zbu.reggie.config.Log;
import com.zbu.reggie.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

//文件上传和下载
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return R.error("请选择上传文件");
        }

        log.info("文件上传：{}", file.getOriginalFilename());
        // 调用阿里云 OSS 工具类进行上传
        try {
            String url = aliOSSUtils.upload(file);
            log.info("文件上传完成，文件的 URL: {}", url);
            return R.success(url);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return R.error("文件上传失败：" + e.getMessage());
        }

    }

    //文件下载
    @Log
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //如果传递的是完整URL，提取对象key
        String objectKey = name;
        if (name.startsWith("https://")) {
            objectKey = name.replace("https://" + aliOSSUtils.getBucketName() + "." + aliOSSUtils.getEndpoint().split("//")[1] + "/", "");
        }

        log.info("尝试下载文件：{}",objectKey);

        response.setContentType("image/jpeg");

        OSS ossClient = null;
        InputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            ossClient = new OSSClientBuilder().build(
                    aliOSSUtils.getEndpoint(),
                    aliOSSUtils.getAccessKeyId(),
                    aliOSSUtils.getAccessKeySecret());

            log.info("尝试下载文件: {}", objectKey);

            if (!ossClient.doesObjectExist(aliOSSUtils.getBucketName(), objectKey)) {
                log.error("文件不存在: {}", objectKey);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("文件不存在");
                return;
            }

            OSSObject ossObject = ossClient.getObject(aliOSSUtils.getBucketName(), objectKey);
            inputStream = ossObject.getObjectContent();

            response.setHeader("Content-Disposition", "inline; filename=\"" + URLEncoder.encode(name, "UTF-8") + "\"");

            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();

            log.info("文件下载成功: {}", name);
        } catch (Exception e) {
            log.error("写入响应失败", e);
            throw new RuntimeException("文件下载失败", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            } catch (IOException e) {
                log.error("关闭资源失败", e);
            }
        }
    }

}
